using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZerAx.Tweaks;

namespace BlockOS.Client
{
    public class ServerListWidget : MonoBehaviour
    {
        [SerializeField]
        private AddServerDialog addServerDialog;
        [SerializeField]
        private ServerListItem itemPrefab;
        [SerializeField]
        private GameObject separatorPrefab;

        public List<(GameObject, ServerListItem)> items = new();

        public Action<string> onItemSelect;

        private void OnEnable()
        {
            GameClient.Instance.EventBus.AddEventHandler(ClientEventId.SERVER_LIST_UPDATE, OnAddServer);
        }

        private void OnDisable()
        {
            GameClient.Instance.EventBus.RemoveEventHandler(ClientEventId.SERVER_LIST_UPDATE, OnAddServer);
        }

        public void OnAddServer(GameEvent e)
        {
            Refresh();
        }

        public void Refresh()
        {
            foreach (var (sep, item) in items)
            {
                if (sep != null) Destroy(sep);
                Destroy(item.gameObject);
            }
            items.Clear();
            foreach(var entry in GameClient.Instance.ServerList.serverEntries)
            {
                AddServer(entry.Key, entry.Value.ToString());
            }
        }

        public void AddServer(string name, string description)
        {
            GameObject sep = null;
            if (items.Count > 0)
            {
                sep = Instantiate(separatorPrefab, transform);
            }
            ServerListItem item = Instantiate(itemPrefab, transform);
            item.SetTitle(name);
            item.SetDescription(description);
            item.editButton.onClick.AddListener(() =>
            {
                var client = GameClient.Instance;
                addServerDialog.modifyName = name;
                client.WindowManager.PushWindow(addServerDialog, WindowManager.PushWindowMode.Addition);
            });
            item.deleteButton.onClick.AddListener(() =>
            {
                var client = GameClient.Instance;
                client.ServerList.serverEntries.Remove(name);
                client.EventBus.AddEvent(new GameEvent(ClientEventId.SERVER_LIST_UPDATE));
            });
            item.onSelect += () =>
            {
                foreach (var (sep, it) in items)
                {
                    if (!ReferenceEquals(it, item)) it.IsSelected = false;
                }
            };
            string n = name;
            item.onChoose = () =>
            {
                onItemSelect?.Invoke(n);
            };
            
            items.Add((sep, item));
        }
    }
}
